using Godot;
using Godot.Collections;
using System;

public partial class EnemyManager : Node
{

	[Export]
	public PackedScene BaseEnemyScene; 
	[Export]
	public PackedScene wizardEnemyScene;
	[Export]
	public ArenaTimeManager arenaTimeManager;
	Timer timer;
	private const int SPAWN_RADIUS = 300;

	double baseSpawnTime  = 0;

	WeightedTable enemyTable = new WeightedTable();
	
	// Called when the node enters the scene tree for the first time.
	public override void _Ready()
	{
		enemyTable.AddItem(BaseEnemyScene,10);


		timer = GetNode("Timer") as Timer;
		timer.Timeout += ()=>{
			this.OnTimerTimeout();
		};

		baseSpawnTime = timer.WaitTime;

		arenaTimeManager.ArenaDifficultyIncreased += OnArenaDifficultyIncreased;
	}

	public Vector2 GetSpawnPosition(){
		Node2D player = GetTree().GetFirstNodeInGroup("player") as Node2D;
		if(player == null){
			return Vector2.Zero;
		}

		Vector2 randomDirection = Vector2.Right.Rotated((float)(new Random().NextDouble()*Math.Tau));
		Vector2 spawnPosition = Vector2.Zero;

		for(int i=0;i<4;i++){
			spawnPosition = player.GlobalPosition + randomDirection * SPAWN_RADIUS;
			Vector2 additionalCheckOffset = randomDirection * 20;
			//两点之间射线检测，有没有碰撞体
			PhysicsRayQueryParameters2D queryParamaters = PhysicsRayQueryParameters2D.Create(player.GlobalPosition,spawnPosition + additionalCheckOffset,1);
			Dictionary result = GetTree().Root.World2D.DirectSpaceState.IntersectRay(queryParamaters);
			if(result.Count == 0){
				break;
			}else{
				randomDirection = randomDirection.Rotated(Mathf.DegToRad(90)); //旋转90度
			}
		}
		
		return spawnPosition;
	}
	
	public void OnTimerTimeout(){
		Node2D player = GetTree().GetFirstNodeInGroup("player") as Node2D;
		if(player == null){
			return;
		}
		PackedScene enemyScene = enemyTable.PickItem();
		Node2D enemy = enemyScene.Instantiate() as Node2D;
		GetTree().GetFirstNodeInGroup("entities_layer").AddChild(enemy);
		// GetParent().AddChild(enemy);
		enemy.GlobalPosition = this.GetSpawnPosition();

		timer.Start();
	}

	public void OnArenaDifficultyIncreased(int arenaDifficulty){
		double timeOff = ( .1/12 ) * arenaDifficulty;
		timeOff = Math.Min(timeOff,.7);
		GD.Print(timeOff);
		timer.WaitTime = baseSpawnTime - timeOff;

		if(arenaDifficulty == 6){
			enemyTable.AddItem(wizardEnemyScene,20);
		}

	}

}
